package com.ncloud.timetask.dao.impl;

import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.utils.JsonUtils;
import com.ncloud.timetask.dao.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by shiqiang on 2017/5/16.
 */
@Repository
public class BaseDaoImpl implements BaseDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Map<String, Object>> commonQuery(String sql) {
        return jdbcTemplate.queryForList(sql);
    }
    @Override
    public List<Map<String, Object>> commonQuery(String sql,JSONObject param) {
        String execSql = JsonUtils.getTemplateInfo(sql,param);
        return jdbcTemplate.queryForList(execSql);
    }
    @Override
    public List<Map<String, Object>> commonQuery(String sql, Object[] param,int[] argTypes) {
        return jdbcTemplate.queryForList(sql,param,argTypes);
    }
  /*  public List<Map<String,Object>> commonQuery2(String sql,Object[] args) {
        List<Map<String,Object>> queryList=jdbcTemplate.query(sql,new MapRowMapper(),args);
        return  queryList;
    }*/

    @Override
    public Map<String, Object> commonQueryOne(String sql) {
        return jdbcTemplate.queryForMap(sql);
    }
    @Override
    public int commonExecute(String sql,Map<String,Object> param){
        int resRow=jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index =0;
                for(Map.Entry entry:param.entrySet()){
                    preparedStatement.setObject(index,entry.getValue());
                }

            }
        });
        System.out.println("操作结果记录数：  "+resRow);
        return resRow;
    }

    @Override
    public int update(String sql, Object[] args, int[] argTypes) {
        return jdbcTemplate.update(sql,args,argTypes);
    }
    /*sql:update user set age=${age},name=${name} where id=${id};insert ...
     * param:{age:10,name:sq,id:123}
      * */
    @Override
    public void execute(String sql , JSONObject param){
        String execSql = JsonUtils.getTemplateInfo(sql,param);
        jdbcTemplate.execute(execSql);
    }
}
